package com.cws.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentFactory;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *  读取系统上传文件的路径的配置文件
 * @author tanxw
 * @since jdk1.6
 * @date 2012-4-13
 *  
 */
public class ConfigUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(ConfigUtil.class);
	
	private static final String SAVE_PATH_ROOT = "save-path-root";
	
	private static final String CONTEXT_URI = "context-uri";
	
	private static final String DOWNLOAD_STRATEGY = "download-strategy";
	
	public static final String NGINX_STRATEGY = "nginx";
	
	public static final String STREAM_STRATEGY = "stream";
	
	public static final String APACHE_STRATEGY = "apache";
	
	public static final String LIGHTTPD_STRATEGY = "lighttpd";
	
	public static final String FTP_PATH_ROOT = "ftp-path-root";
	public static final String FTP_USER_PATH = "ftp-user-path";

    /**
     * 附件保存路径中与当前日期和时间相关的值相对应的正则表达式模式，该模式中各字母表示的含义请参见： <a href=
     * "http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html"
     * target="_blank">http://docs.oracle.com/javase/6/docs/api/java/text/
     * SimpleDateFormat.html</a>
     */
    protected static final Pattern SAVE_PATH_DATE_PATTERN = Pattern.compile("%([yMwWDdFEHkKhmsS /.:\\-]+)%");

	/**
	 * cache config
	 */
	protected static Properties props = new Properties();
	
	protected ConfigUtil() {
	}
	
	static {
		DocumentFactory df = DocumentFactory.getInstance();
		SAXReader reader = new SAXReader(df);
		Document document = null;
		InputStream resourceAsStream = null;
		// 取得XML路
		try {
			//优先读取web root下面的配置文件，如果没有再读取默认配置文件
			
			String WebRootPath = ConfigUtil.class.getClassLoader().getResource("").getPath();
			File file = new File(WebRootPath, "WEB-INF/config/upload.xml");
			if (file.exists()) {
				resourceAsStream = new FileInputStream(file);
			}
			
			//读取默认配置文件
			if (null == resourceAsStream) {
				resourceAsStream = ConfigUtil.class.getClassLoader().getResourceAsStream("upload.xml");
			}
			
			document = reader.read(resourceAsStream);
			//String separator = System.getProperty("file.separator");
			
			//取得下载上下文路径
			String contextPath = document.selectSingleNode("/upload/context-uri").getText().trim();
			props.put(CONTEXT_URI, ensurePath(contextPath));
			Node downStrategyNode = document.selectSingleNode("/upload/download-strategy");
			if (null != downStrategyNode && null != downStrategyNode.getText()) {
				props.put(DOWNLOAD_STRATEGY, downStrategyNode.getText().trim());
			}
			//取得保存文件的根路径
			String savepathRoot = "";
			//取得保存FTP更路径 /FTP用户路径
			String ftppathRoot = "";
			String ftpuserPath = "";
			if (isWindows()) {
				savepathRoot = document.selectSingleNode("/upload/save-path/windows").getText().trim();
				ftppathRoot = document.selectSingleNode("/upload/ftp-path/windows").getText().trim();
			} else {
				savepathRoot = document.selectSingleNode("/upload/save-path/linux").getText().trim();
				ftppathRoot = document.selectSingleNode("/upload/ftp-path/linux").getText().trim();
			}
			props.put(SAVE_PATH_ROOT, ensurePath(savepathRoot));
			
			ftpuserPath = document.selectSingleNode("/upload/ftp-path/ftp-user-path").getText().trim();
			props.put(FTP_USER_PATH, ensurePath(ftpuserPath));
			props.put(FTP_PATH_ROOT, ensurePath(ftppathRoot));
		
			
		} catch (Exception e) {
			logger.error("读取文件上传的配置文件出错！", e);
		}
	}
	
	public static String getDownloadStrategy() {
		return props.getProperty(DOWNLOAD_STRATEGY, NGINX_STRATEGY);
	}
	

	/**
	 *根据原始文件名生成新的文件名 ：即当前时间戳＋4位随机数+原始扩展名 
	 * @param fileName
	 * @return 生成的新文件名
	 */
	public static String genearteNewFilename(String originalName) {
		int pos = -1;
		String extName = "";
		if (StringUtils.isNotEmpty(originalName)) {
			pos = originalName.lastIndexOf(".");
		}
		if (pos != -1) {
			extName = originalName.substring(pos);
		}
		String filenamePrefix = String.valueOf(new Date().getTime());
		String filename = filenamePrefix + RandomStringUtils.randomNumeric(4) + extName;
		return filename;
	}
	
	/**
	 * @return context down path, it always end with "/", eg: "files/".
	 */
	public static String getDownloadContextPath() {
		String contextPath = props.getProperty(CONTEXT_URI);
		return ensurePath(contextPath);
	}
	
	/**
	 * make sure the path end with "/"
	 * @param path
	 * @return
	 */
	public static String ensurePath(String path) {
		path = path.replace("\\", "/");
		
		if (!path.endsWith("/")) {
			path += "/";
		}
		return path;
	}
	
	/**
	 * @return fiel save path root, it always end with "/", eg: "c:/files/".
	 */
	public static String getSavepathRoot() {
		String root = props.getProperty(SAVE_PATH_ROOT);
		return ensurePath(root);
	}
	
	public static boolean isWindows() {
		String os = System.getProperty("os.name");
		return null != os && os.indexOf("Windows") != -1;
	}
	
	public static void main(String[] args) throws DocumentException {
		
		System.out.print(ensurePath("a\\a\\a"));
	}
	
	public static String getFtppathRoot() {
		String root = props.getProperty(FTP_PATH_ROOT);
		return ensurePath(root);
	}
	public static String getFtpuserPath() {
		String root = props.getProperty(FTP_USER_PATH);
		return ensurePath(root);
	}
}
